import { computed, reactive, ref } from 'vue';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
import type { TokenInfo, UsrPwdParam } from '@/service/api/login';
import { usrpwdLogin } from '@/service/api/login';
import { isSuccess } from '@/utils/response';
import { useRouteStore } from '../route';
import { clearAuthStorage, getToken, getUserInfo } from './shared';

/** 用户名密码+图片验证码登录 */
export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const routeStore = useRouteStore();
  const { route, toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive(getUserInfo());

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    const authStore = useAuthStore();

    clearAuthStorage();

    authStore.$reset();

    if (!route.value.meta.constant) {
      await toLogin();
    }

    routeStore.resetStore();
  }

  /** Username password login */
  async function loginByUsrPwd(params: UsrPwdParam) {
    startLoading();

    const response = await usrpwdLogin(params);
    if (isSuccess(response)) {
      const pass = await loginByToken(response.data);

      if (pass) {
        await routeStore.initAuthRoute();

        await redirectFromLogin();

        if (routeStore.isInitAuthRoute) {
          window.$notification?.success({
            title: $t('page.login.common.loginSuccess'),
            content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
            duration: 4500
          });
        }
      }
    } else {
      resetStore();
    }

    endLoading();
  }

  async function loginByToken(loginToken: TokenInfo) {
    // 1. stored in the localStorage, the later requests need it in headers
    localStg.set('token', loginToken.token);
    localStg.set('refreshToken', loginToken.token);

    // 查询用户信息
    const user = {
      userName: loginToken.user.username,
      userId: loginToken.user.userid,
      roles: loginToken.user.privileges
    };

    // 2. store user info
    localStg.set('userInfo', user);

    // 3. update auth route
    token.value = loginToken.token;
    Object.assign(userInfo, user);

    return true;
  }

  return {
    token,
    userInfo,
    isLogin,
    loginLoading,
    resetStore,
    loginByUsrPwd
  };
});
